package com.xuxueli.applyModules.utils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xuxueli.applyModules.entity.DcBillHeadTmpParam;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 发起api请求
 */
@Slf4j
public class ApiForwardRequest2 {
    private static final String DEF_CHATSET = "UTF-8";
    private static final int DEF_CONN_TIMEOUT = 60000;
    private static final int DEF_READ_TIMEOUT = 60000;
    /**
     * 以下参数在 resource\api.properties 中配置
     * @param strUrl  访问地址路径url
     * @param params  提交的参数map集合 (list head tradeCode I_E_FLAG key)
     * @param method  访问方式GET或者POST
     * @param token   权限验证，如果没有选择空即可
     * @return
     * @throws Exception
     */
    public static String net(String strUrl, Map<String,Object> params, String method, String token) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        String rs = null;
        try {
            if(method.equals("GET") || method == null){
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type","application/json");
                conn.setRequestProperty("Content-Length","content.length");
            }
            conn.setRequestProperty("Authorization",token);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                String sendStr = JSONObject.toJSONString(params, SerializerFeature.WriteMapNullValue);
                log.info("报关单打印请求数据：" + sendStr);
                out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
                out.append(sendStr);
                out.flush();
                out.close();
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = "";
            StringBuffer strBuffer = new StringBuffer();
            while ((strRead = reader.readLine()) != null) {
                strBuffer.append(strRead);
            }
            rs = strBuffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                reader.close();
            }
            if (null != conn) {
                conn.disconnect();
            }
            if (null != out) {
                out.close();
            }
        }
        return rs;
    }
    //将map型转为请求参数型（get访问时使用）
    public static String urlencode(Map<String, Object> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");


    public static String post(String url, String token, String json) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(1800, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(1800, TimeUnit.SECONDS)//设置读取超时时间
                .build();
        client.writeTimeoutMillis();
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", token)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static void main(String[] args) {
        Map<String, Object> reqData = new HashMap();
        reqData.put("HEAD", new DcBillHeadTmpParam());
        reqData.put("LIST", new ArrayList<>());
        String urlRequest = "";
        try {
            urlRequest = ApiForwardRequest2.net("http://128.0.0.1:8089/getuserom",reqData, "POST", "bearer " + "sfwefsfsacdsa");
        }catch (Exception e){
            ResultObject.createInstance(false, "请求打印接口出错:"+e.getMessage());
        }
    }

}
